const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const cors = require('cors');
const fs = require('fs').promises;
const path = require('path');
require('dotenv').config();

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "http://localhost:3000",
    methods: ["GET", "POST"]
  }
});

// 中间件
app.use(cors({
  origin: "http://localhost:3000",
  methods: ["GET", "POST"]
}));
app.use(express.json());

// 确保数据目录存在
const DATA_DIR = path.join(__dirname, 'data');
const MESSAGES_FILE = path.join(DATA_DIR, 'messages.json');

// 初始化数据目录和文件
async function initializeData() {
  try {
    await fs.mkdir(DATA_DIR, { recursive: true });
    try {
      await fs.access(MESSAGES_FILE);
    } catch {
      await fs.writeFile(MESSAGES_FILE, JSON.stringify([]));
    }
  } catch (err) {
    console.error('初始化数据目录失败:', err);
  }
}

initializeData();

// 存储在线用户
const onlineUsers = new Map();

// Socket.IO 连接处理
io.on('connection', (socket) => {
  console.log('New client connected');

  // 发送当前在线用户列表
  socket.emit('userList', Array.from(onlineUsers.values()));

  socket.on('join', (user) => {
    // 检查用户是否已存在
    if (!onlineUsers.has(user.id)) {
      onlineUsers.set(user.id, user);
      socket.userId = user.id;
      io.emit('userJoined', { 
        user,
        message: `${user.username} 加入了聊天室` 
      });
      // 更新所有客户端的用户列表
      io.emit('userList', Array.from(onlineUsers.values()));
    }
  });

  socket.on('leave', (user) => {
    if (onlineUsers.has(user.id)) {
      onlineUsers.delete(user.id);
      io.emit('userLeft', { 
        user,
        message: `${user.username} 离开了聊天室` 
      });
      // 更新所有客户端的用户列表
      io.emit('userList', Array.from(onlineUsers.values()));
    }
  });

  // 敏感词列表
  const sensitiveWords = ['傻瓜', '笨蛋', '白痴', '垃圾', '废物', '混蛋'];

  // 过滤敏感词函数
  const filterSensitiveWords = (text) => {
    let filteredText = text;
    sensitiveWords.forEach(word => {
      const regex = new RegExp(word, 'gi');
      filteredText = filteredText.replace(regex, '*'.repeat(word.length));
    });
    return filteredText;
  };

  socket.on('message', (data) => {
    // 过滤消息中的敏感词
    const filteredMessage = filterSensitiveWords(data.message);
    
    const messageObj = {
      id: Date.now().toString(), // 添加唯一ID用于撤回功能
      userId: data.userId,
      username: onlineUsers.get(data.userId)?.username || '未知用户',
      message: filteredMessage,
      timestamp: new Date()
    };
    
    io.emit('message', messageObj);
  });
  
  // 处理消息撤回
  socket.on('recallMessage', (messageId) => {
    const user = onlineUsers.get(socket.userId);
    if (user) {
      io.emit('messageRecalled', {
        id: messageId,
        userId: user.id,
        username: user.username,
        message: '此消息已被撤回',
        timestamp: new Date()
      });
    }
  });

  socket.on('disconnect', () => {
    if (socket.userId && onlineUsers.has(socket.userId)) {
      const user = onlineUsers.get(socket.userId);
      onlineUsers.delete(socket.userId);
      io.emit('userLeft', { 
        user,
        message: `${user.username} 离开了聊天室` 
      });
      // 更新所有客户端的用户列表
      io.emit('userList', Array.from(onlineUsers.values()));
    }
  });
});

const PORT = process.env.PORT || 3001;
server.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});